import { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Upload, BarChart3, Loader2, FileText, TrendingUp } from 'lucide-react';
import { chartApi } from '@/services/api';
import { useToast } from '@/hooks/use-toast';
import ReactECharts from 'echarts-for-react';

export function AnalysisPage() {
  const [formData, setFormData] = useState({
    name: '',
    goal: '',
    chartType: '',
  });
  const [file, setFile] = useState<File | null>(null);
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState<any>(null);
  const { toast } = useToast();


  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFile = e.target.files?.[0];
    if (selectedFile) {
      setFile(selectedFile);
    }
  };

  const handleSubmit = async () => {
    if (!formData.name || !formData.goal || !file) {
      toast({
        title: "请填写完整信息",
        description: "请确保填写图表名称、分析目标并上传数据文件",
        variant: "destructive",
      });
      return;
    }

    setLoading(true);
    try {
      const formDataToSend = new FormData();
      formDataToSend.append('name', formData.name);
      formDataToSend.append('goal', formData.goal);
      formDataToSend.append('chartType', formData.chartType);
      formDataToSend.append('file', file);

      // 使用同步接口
      const response = await chartApi.genChartByAi(formDataToSend);
      
      if (response.code === 0) {
        setResult(response.data);
        toast({
          title: "分析成功",
          description: "图表已生成，请查看结果",
        });
      } else {
        throw new Error(response.message);
      }
    } catch (error: any) {
      toast({
        title: "分析失败",
        description: error.message || "请稍后重试",
        variant: "destructive",
      });
    } finally {
      setLoading(false);
    }
  };

  const handleReset = () => {
    setFormData({ name: '', goal: '', chartType: '' });
    setFile(null);
    setResult(null);
  };

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <div className="flex items-center space-x-3">
        <BarChart3 className="h-8 w-8 text-blue-600" />
        <div>
          <h1 className="text-3xl font-bold text-gray-900">智能分析</h1>
          <p className="text-gray-600">上传数据，AI 智能生成图表和分析结论</p>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* 左侧：配置表单 */}
        <Card className="shadow-lg border-0 bg-white">
          <CardHeader className="bg-gradient-to-r from-blue-50 to-cyan-50 border-b">
            <CardTitle className="flex items-center space-x-2">
              <FileText className="h-5 w-5 text-blue-600" />
              <span>分析配置</span>
            </CardTitle>
          </CardHeader>
          <CardContent className="p-6 space-y-6">
            {/* 分析目标 */}
            <div className="space-y-2">
              <Label htmlFor="goal" className="text-sm font-medium text-gray-700">
                分析目标 <span className="text-red-500">*</span>
              </Label>
              <Textarea
                id="goal"
                placeholder="请描述你的分析需求，例如：分析网站用户的增长情况"
                value={formData.goal}
                onChange={(e) => setFormData({ ...formData, goal: e.target.value })}
                className="min-h-[100px] resize-none"
              />
            </div>

            {/* 图表名称 */}
            <div className="space-y-2">
              <Label htmlFor="name" className="text-sm font-medium text-gray-700">
                图表名称 <span className="text-red-500">*</span>
              </Label>
              <Input
                id="name"
                placeholder="请输入图表名称"
                value={formData.name}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
              />
            </div>

            {/* 图表类型 */}
            <div className="space-y-2">
              <Label className="text-sm font-medium text-gray-700">图表类型</Label>
              <Select value={formData.chartType} onValueChange={(value) => setFormData({ ...formData, chartType: value })}>
                <SelectTrigger>
                  <SelectValue placeholder="请选择图表类型" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="柱状图">柱状图</SelectItem>
                  <SelectItem value="折线图">折线图</SelectItem>
                  <SelectItem value="饼图">饼图</SelectItem>
                  <SelectItem value="散点图">散点图</SelectItem>
                  <SelectItem value="雷达图">雷达图</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {/* 原始数据 */}
            <div className="space-y-2">
              <Label className="text-sm font-medium text-gray-700">
                原始数据 <span className="text-red-500">*</span>
              </Label>
              <div className="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-blue-400 transition-colors">
                <input
                  type="file"
                  accept=".csv,.xlsx,.xls"
                  onChange={handleFileChange}
                  className="hidden"
                  id="file-upload"
                />
                <label htmlFor="file-upload" className="cursor-pointer">
                  <Upload className="h-8 w-8 text-gray-400 mx-auto mb-2" />
                  <p className="text-sm text-gray-600">
                    {file ? file.name : '上传 CSV 文件'}
                  </p>
                  <p className="text-xs text-gray-400 mt-1">
                    支持 CSV、Excel 格式
                  </p>
                </label>
              </div>
            </div>

            {/* 操作按钮 */}
            <div className="flex space-x-3 pt-4">
              <Button 
                onClick={handleSubmit} 
                disabled={loading}
                className="flex-1 bg-blue-600 hover:bg-blue-700"
              >
                {loading ? (
                  <>
                    <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                    分析中...
                  </>
                ) : (
                  '提交'
                )}
              </Button>
              <Button 
                variant="outline" 
                onClick={handleReset}
                className="flex-1"
              >
                重置
              </Button>
            </div>
          </CardContent>
        </Card>

        {/* 右侧：分析结果 */}
        <div className="space-y-6">
          {/* 分析结论 */}
          <Card className="shadow-lg border-0 bg-white">
            <CardHeader className="bg-gradient-to-r from-green-50 to-emerald-50 border-b">
              <CardTitle className="flex items-center space-x-2">
                <TrendingUp className="h-5 w-5 text-green-600" />
                <span>分析结论</span>
              </CardTitle>
            </CardHeader>
            <CardContent className="p-6">
              {result ? (
                <div className="text-sm text-gray-700 leading-relaxed">
                  {result.genResult}
                </div>
              ) : (
                <div className="flex flex-col items-center justify-center py-12 text-center">
                  <TrendingUp className="h-12 w-12 text-gray-300 mb-4" />
                  <p className="text-gray-500 text-sm">
                    提交分析请求后，AI 将为您生成详细的分析结论
                  </p>
                </div>
              )}
            </CardContent>
          </Card>

          {/* 可视化图表 */}
          <Card className="shadow-lg border-0 bg-white">
            <CardHeader className="bg-gradient-to-r from-purple-50 to-pink-50 border-b">
              <CardTitle>可视化图表</CardTitle>
            </CardHeader>
            <CardContent className="p-6">
              {result && result.genChart ? (
                <div className="h-80">
                  {/* 渲染ECharts图表 */}
                  <ReactECharts
                    option={typeof result.genChart === 'string' ? JSON.parse(result.genChart) : result.genChart}
                    style={{ height: '100%', width: '100%' }}
                    opts={{ renderer: 'canvas' }}
                  />
                </div>
              ) : (
                <div className="flex flex-col items-center justify-center py-16 text-center">
                  <BarChart3 className="h-16 w-16 text-gray-300 mb-4" />
                  <p className="text-gray-500 text-sm mb-2">
                    暂无图表数据
                  </p>
                  <p className="text-gray-400 text-xs">
                    上传数据文件并提交分析请求后，这里将显示生成的图表
                  </p>
                </div>
              )}
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}